package com.oldou.dao;

import com.oldou.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@Repository
public class UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 保存用户
     */
    public void save(User user){
        String sql = "insert into user (id,name,pwd) values(?,?,?)";
        jdbcTemplate.update(sql,user.getId(),user.getName(),user.getPwd());
    }

    /**
     * 根据ID更新用户信息
     */
    public void updateUser(User user){
        String sql = "update user set name=?,pwd=? where id=?";
        jdbcTemplate.update(sql,user.getName(),user.getPwd(),user.getId());
    }

    /**
     * 根据ID删除用户
     */
    public void delete(int id){
        String sql = "delete from user where id = ?";
        jdbcTemplate.update(sql,id);
    }

    /**
     * 查询全部用户
     */
    public List<Map<String, Object>> QueryAll(){
        String sql = "select * from user";
        return jdbcTemplate.queryForList(sql);
    }
    /**
     * 根据ID查询用户
     */
    public User QueryUserByID(int id){
        String sql = "select * from user where id = ?";
        return jdbcTemplate.queryForObject(sql, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setName(rs.getString("name"));
                user.setPwd(rs.getString("pwd"));
                return user;
            }
        },id);
    }
}
